﻿//'angularFileUpload',
var Coursmaking = angular.module("Coursmaking", ['angular-sortable-view', 'angularFileUpload', 'Common', 'knowledgebaseS', 'wangeditordrective', 'knowledgeSelector', 'courseScript', 'personnelmanagementS', 'PensonSelector'])

//鼠标聚焦事件
.directive('myFocus', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            //            scope.$watch(attr.myFocus, function (n, o) {
            //                if (n != 0 && n) {
            element[0].focus();
            //                }
            //            });
        }
    };
})
//鼠标失焦事件
.directive('myBlur', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('blur', function () {
                scope.$apply(attr.myBlur);
                //scope.$eval(attr.myFocus + '=false');
            });
        }
    };
})
//"FileUploader", FileUploader,
.controller("lukecheng", ['$rootScope', "$scope", "MsgCon", "sysUserInfo", "RequestTrainService", 'Msg', 'updateUrl', "$timeout", 'FileUploader', '$sce', '$stateParams', '$state', 'RequestPopService', 'T', 'requestStatisticService', function ($rootScope, $scope, MsgCon, sysUserInfo, RS, Msg, updateUrl, $timeout, FileUploader, $sce, $stateParams, $state, RPS, T, requestStatisticService) {
    $scope.TrainResult = false; //培训结果
    $scope.TrainTime = false; //培训时间
    $scope.TrainPlan = false; //培训计划
    $scope.isbtnload = false;
    $scope.typeposition = ""; //查看更多类型位置
    $scope.rcoursimg = false;
    $rootScope.btnTab = "index.Train.course";
    //    $scope.typeshow = false;   
    // 判断课程id是否空
    // 修改时提示
    $scope.tishi = function () {
        alert(1);
    }

    //已学习人数
    $scope.studyCount = 0;
    //    if ($stateParams.studycount != undefined && $stateParams.studycount != null) {
    //        $scope.studyCount = $stateParams.studycount;
    //    }
    $scope.courseToast = function (text, flag) {
        //        if (!($stateParams.courid == undefined || $stateParams.courid == null || $stateParams.courid == "" || $stateParams.courid == 0 || $stateParams.courid == "0")) {
        //            return MsgCon.delnoicon("注意" + text, "学员的进度信息不会马上响应,学员需要在下次学习本课程时进行数据矫正.</br>", { html: true }, "确定", "");
        //        }
        // 删除章节
        if (flag)
            return MsgCon.delnoicon();
    }
    $scope.initAddChapter = true; //判断新增章节

    $scope.detailedJSON = []; //章节集合
    //    $scope.traininfo = { courseId: "", courseName: "", lecturer: "", detailedJSON: $scope.detailedJSON, titype: "", courseImg: "" }; //课件对应的集合
    $scope.traininfo = { courseImg: "/images/train/fengmian001.gif", lecturer: sysUserInfo.getuserinfo().username, isOpen: 0, integral: 0, courseDetailed: { introduce: "", fileList: []} }; // {"knowledgeJSON":"","knowledgeId":"888888","isOpen":"0","courseOrder":"0","courseId": "", "courseName": "课程名称", "lecturer": "教师名称", "detailedJSON": [{ "chid": "20170713165726168", "chapter": "第一章", "content": [{ "CSID": "20170713165726168", "CSNAME": "我是图文", "$$hashKey": "object:127", "CSTYPE": "8", "stypename": "图文类型", "stypeicon": "#icon-kaoshi1", "fileTxt": "<span style=\"color: rgb(51, 51, 51); font-family: arial; font-size: 13px;\">摘要: 本文章就是介绍两个</span><span style=\"color: rgb(204, 0, 0); font-family: arial; font-size: 13px;\">解码</span><span style=\"color: rgb(51, 51, 51); font-family: arial; font-size: 13px;\">的函数,他们就是decodeURI()和</span><span style=\"color: rgb(204, 0, 0); font-family: arial; font-size: 13px;\">decodeURIComponent</span><span style=\"color: rgb(51, 51, 51); font-family: arial; font-size: 13px;\">()函数,这两个函数可以对特定函数生成的密码字符串进行解密操作,就可以生成为未解密</span><br>", "CSTITLE": "摘要: 本文章就是介绍两", "chshow": false, "CSdescribe": "简介内容1", "manage_imgtext": false }, { "CSID": "2017071316584925", "CSNAME": "我是视频", "$$hashKey": "object:200", "CSTYPE": "1", "stypename": "视频类型", "stypeicon": "#icon-shipin", "chshow": false, "CSdescribe": "简介内容2", "CSURL": "https://www.baidu.com", "manage_video": false}], "$$hashKey": "object:118"}], "titype": "", "courseImg": "http://180.76.156.234:8189/Fast-Trianing-FileCenter/resources/knowledge/0/1/6ed040f8-00a6-4baa-954f-25634bf95b33/1.jpg" };

    //新增章节的可选类型
    $scope.typelist = [{ "typeid": "1", "typename": "视频", "typeicon": "#icon-shipin4", "sel": "false" },
    { "typeid": "2", "typename": "文档", "typeicon": "#icon-intro", "sel": "false" },
    { "typeid": "8", "typename": "图文", "typeicon": "#icon-tupian1", "sel": "false" },
    {"typeid": "3", "typename": "试卷", "typeicon": "#icon-icon04", "sel": "false" }
    ];

    $scope.chapterNumList = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];

    $scope.amountJSON = { "order": "0", "play": "0", "forward": "0", "collection": "0", "download": "0", "like": "0" };
    //{"order":"1",//顺序号"play":"33",//播放量"forward":"222",//转发量"collection":"111",//收藏量"download":"500",//下载量"like":"1",//点赞量}

    //下载录播
    $scope.DownLive = function (obj) {
        if ($scope.livebtnload) {
            return;
        }
        if (obj.liveObj.recordHtm == undefined || obj.liveObj.recordHtm == null || obj.liveObj.recordHtm.length <= 0) {
            Msg.info("正在下载录播视频。。。");
            $scope.livebtnload = true;
            RS.generateVideo({ uid: sysUserInfo.getuserinfo().user_ID, roomId: obj.liveObj.roomId }).then(function (response) {
                if (response.errorcode == 0) {
                    obj.liveObj.recordHtm = response.data.recordHtm; //这里回写一下
                    Msg.success("保存成功！");
                } else if (response.errorcode == 25) {
                    Msg.warning("录播视频还未生成，请稍后再试！");
                } else if (response.errorcode == 26) {
                    Msg.warning("直播间不存在！");
                } else {
                    Msg.error("录播视频存储失败！");
                }
                $scope.livebtnload = false;
            }, function (e) {
                Msg.error("录播视频存储失败！");
                $scope.livebtnload = false;
            });
        } else {
            Msg.warning("该直播已完成视频存储！");
        }
    }

    //新增小节（选内容）
    $scope.addke = function (obj) {
        //自动追加课程小节，追加位置，最后一章尾部
        var csid = $scope.getnewid();
        var newxiaojie = { "CSID": csid, "CSNAME": "", "CSTYPE": obj.typeid, "stypeicon": obj.typeicon, "stypename": obj.typename, "chshow": true };
        //视频或文档，默认播放时长1分钟
        if (obj.typeid == 1 || obj.typeid == "1" || obj.typeid == 2 || obj.typeid == "2") {
            newxiaojie.CSTIME = "1";
        }
        //直播类型，默认obs视频直播
        if (obj.typeid == 6 || obj.typeid == "6") {
            newxiaojie.livetype = "2";
        }
        if ($scope.detailedJSON.length < 1) {
            $scope.initAddChapter = false;
            //如果还没有章节，自动加一个
            $scope.detailedJSON.push({ "chid": $scope.getnewid(), "chapter": "第" + $scope.chapterNumList[$scope.detailedJSON.length] + "章", content: [newxiaojie] });
        }
        else {
            newxiaojie.index = $scope.detailedJSON[$scope.detailedJSON.length - 1].content.length + 1;
            $scope.detailedJSON[$scope.detailedJSON.length - 1].content.push(newxiaojie); //插入最后一个章节中
        }
        switch (obj.typeid) {
            case "1": //视频（选文件）
                $scope.openChapter(newxiaojie, true);
                break;
            case "2": //文档
                $scope.openChapter(newxiaojie, true);
                //执行代码块 2
                break;

            case "6"://直播
                $scope.openLiveSelect(newxiaojie);
                break;
            default:
                $scope.shezhi(newxiaojie, $scope.detailedJSON[$scope.detailedJSON.length - 1].chid);
                //未知类型，啥也不做
                break;
        }
    }


    //新增章节
    $scope.AddChapterFun = function () {
        $scope.initAddChapter = false;
        $scope.sectioninfo = { "CSID": $scope.getnewid(), "CSNAME": "", "chshow": true }; //小节集合, "stypeid": "2", "stypename": "文档类型", "stypeicon": "#icon-txt1"
        $scope.detailedJSON.push({ "chid": $scope.getnewid(), "chapter": "第" + $scope.convertNum($scope.detailedJSON.length + 1) + "章", content: [$scope.sectioninfo] });
        $scope.courseToast("【新增章节】");
    }
    //数字转汉字
    $scope.convertNum = function (num) {
        num = num.toString();
        var newchar = "";
        for (var i = 0; i < num.length; i++) {
            var tmpnewchar = ""
            var perchar = num.charAt(i);
            switch (perchar) {
                //case "0": tmpnewchar = "零" + tmpnewchar; break;                                                                                                                                   
                case "1": tmpnewchar = "一" + tmpnewchar; break;
                case "2": tmpnewchar = "二" + tmpnewchar; break;
                case "3": tmpnewchar = "三" + tmpnewchar; break;
                case "4": tmpnewchar = "四" + tmpnewchar; break;
                case "5": tmpnewchar = "五" + tmpnewchar; break;
                case "6": tmpnewchar = "六" + tmpnewchar; break;
                case "7": tmpnewchar = "七" + tmpnewchar; break;
                case "8": tmpnewchar = "八" + tmpnewchar; break;
                case "9": tmpnewchar = "九" + tmpnewchar; break;
            }
            switch (num.length - i - 1) {
                //case 0: tmpnewchar = tmpnewchar + ""; break;                                                                                                                                   
                case 1: if (perchar != 0) tmpnewchar = tmpnewchar + "十"; break;
                case 2: if (perchar != 0) tmpnewchar = tmpnewchar + "百"; break;
                case 3: if (perchar != 0) tmpnewchar = tmpnewchar + "千"; break;
                case 4: tmpnewchar = tmpnewchar + "万"; break;
                case 5: if (perchar != 0) tmpnewchar = tmpnewchar + "十"; break;
                case 6: if (perchar != 0) tmpnewchar = tmpnewchar + "百"; break;
                case 7: if (perchar != 0) tmpnewchar = tmpnewchar + "千"; break;
                case 8: tmpnewchar = tmpnewchar + "亿"; break;
                case 9: tmpnewchar = tmpnewchar + "十"; break;
            }
            newchar = newchar + tmpnewchar;
            //console.log(newchar);
        }
        return newchar;
    }
    //  播放  CS_play
    //  点赞  CS_praise
    //  收藏  CS_ collect
    //  下载  CS_down
    //  是否下载  CS_isdown
    //学习时间 CS_learntime
    //    是否指定学习人数 CS_learnpeople

    //控制是否允许下载
    $scope.allow_down = function (kechengtype) {
        if (kechengtype.CS_isdown) { kechengtype.CS_isdown = false; } else { kechengtype.CS_isdown = true; }
    }
    //是否指定学习人数
    $scope.allow_learnpeople = function (secinfo) {
        if (secinfo.CS_learnpeople) { secinfo.CS_learnpeople = false; } else { secinfo.CS_learnpeople = true; }
    }


    //新增小节
    $scope.AddSection = function (chid) {
        $scope.detailedJSON.forEach(function (item, index) {
            if (item.chid == chid) {
                $scope.sectioninfo = { "CSID": $scope.getnewid(), "CSNAME": "", "chshow": true }; //小节集合 , "stypeid": "2", "stypename": "文档类型", "stypeicon": "#icon-txt1"
                $scope.detailedJSON[index].content.push($scope.sectioninfo);
                return;
            }
        });
    }
    $scope.secinfo = "";
    //查看更多类型
    $scope.typemore = function (event, secinfo) {
        $scope.secinfo = secinfo;
        var e = event || window.event; //捕获鼠标位置，控制更多显示的位置
        /*
        console.log(e.clientX + "_" + e.clientY);
        console.log(window.innerWidth + "_" + window.innerHeight);
        */
        if ($scope.secinfo.typeshow) {
            $scope.secinfo.typeshow = false;
        } else {
            $scope.typeposition = { "right": "-70px", "top": "30px", "z-index": "9" };
            $scope.secinfo.typeshow = true;
        }
    }


    //选择小节后对应的操作控制
    $scope.courcontent = { "courcontent_video": false, "courcontent_file": false, "courcontent_live": false, "courcontent_offline": false, "courcontent_ques": false, "courcontent_exam": false, "courcontent_imgtext": false, "courcontent_covert": false, "courcontent_more": false };

    //选择课件小节的类型
    //更改显示各种类型小节对应的样式
    //6种类型样式显示控制（视频、文档、直播课件、线下课程、题库、考试）
    $scope.seltype = function (typeitem, chid, secinfo) {
        $scope.secinfo = secinfo;
        //$scope.typeshow = false;
        $scope.secinfo.typeshow = false;

        $scope.secinfo.CSTYPE = typeitem.typeid;
        $scope.secinfo.stypename = typeitem.typename;
        $scope.secinfo.stypeicon = typeitem.typeicon;
        $scope.secinfo.CS_learnpeople = false;
        if (typeitem.typeid == 8) {//图文类型时 弹出图文对应的录入框
            $scope.courcontent.courcontent_imgtext = true;
        }

    }
    //删除小节
    $scope.delxiaojei = function (chid, CSID, flag) {
        $scope.detailedJSON.forEach(function (item, index) {
            if (item.chid == chid) {
                $scope.detailedJSON[index].content.forEach(function (item2, index2) {
                    if (CSID == item2.CSID) {
                        delIndex = item2.index;
                        $scope.detailedJSON[index].content.splice(index2, 1);
                        return;
                    }
                });
            }
        });
        if (flag != 1)
            $scope.courseToast("【删除小节】");
    }
    $scope.kechengtype = {}; //用于设置小节类型
    $scope.ke_system = false;

    $scope.liveUrl="";
    //设置小节类型
    $scope.shezhi = function (obj, chid) {
        // if (obj.CSTYPE == 6 && obj.hasOwnProperty("liveObj")) {

        //         // RS.liveBroadcast({uid:sysUserInfo.getuserinfo().user_ID,roomId:obj.liveObj.roomId}).then(function (response) {
        //         //     if (response.errorcode == 0) {

        //         //     }else if(response.errorcode == 0){
                        
        //         //     }

        //         // });
                
        //     $scope.liveUrl=obj.liveObj.teachHtm + "?lid=" + obj.liveObj.roomId;
        //     $timeout(function () { document.getElementById("liveUrl").click(); }, 50);
        //     return;
        // }
        if ($scope.studyCount > 0) {
            Msg.warning("提示", "该课程已有学员学习，不允许修改内容！");
            return;
        }
        $scope.ke_system = true; //显示窗口
        $scope.kechengtype = angular.copy(obj);
        $scope.kechengtype.chid = chid; //标识下，这是那一章节的
        $scope.gaitype(obj.CSTYPE); //设置选中项目

    }
    //设置完成,关闭设置界面
    $scope.shezhiedu = function (obj) {

        if (obj) {
            //默认为一
            if ((obj.CSTIME <= 0 || obj.CSTIME == undefined || obj.CSTIME == "" || obj.CSTIME == null)
            	&& (obj.CSTYPE == "2" || obj.CSTYPE == "1")) {
                obj.CSTIME = 1;
            }
            //验证时间
            if ((obj.CSTYPE == "2" || obj.CSTYPE == "1") && (obj.CSTIME < 0 || obj.CSTIME.toString().indexOf(".", "+", "-") != -1)) {
                Msg.warning("请输入大于0的正整数");
                return;
            }

            //********************************************新直播类型*********************************************

            // //直播类型
            // if (obj.CSTYPE == "6") {
            //     if (obj.liveObj && obj.liveObj != "") {
            //         Msg.error("直播创建后无法修改");
            //         return false;
            //     }
            //     if (obj.livetype == undefined || obj.livetype == null || obj.livetype.length <= 0) {
            //         Msg.warning("请选择直播类型！");
            //         return;
            //     }
            //     if (obj.CSSTIME == undefined || obj.CSSTIME.length <= 0) {
            //         Msg.warning("请选择开播日期！");
            //         return;
            //     }
            //     if (obj.livetype == 3 && (obj.CSETIME == undefined || obj.CSETIME.length <= 0)) {
            //         Msg.warning("请选择结束日期！");
            //         return;
            //     }

            //     //开始创建直播
            //     $scope.islivebtnload = true;
            //     //请求直播
            //     $scope.liveParams = {
            //         liveName: obj.CSNAME,
            //         livePwd: obj.PWD,
            //         liveYue: false,
            //         liveType: obj.livetype,
            //         liveStateTime: obj.CSSTIME,
            //         createOid: sysUserInfo.getuserinfo().organization_ID,
            //         createUname: sysUserInfo.getuserinfo().organization_Name,
            //         createUid: sysUserInfo.getuserinfo().user_ID,
            //         createUname: sysUserInfo.getuserinfo().user_Name,
            //         pnumber: obj.CSPNUM
            //     };

            //     RS.saveLive($scope.liveParams).then(function (response) {
            //         if (response.errorcode == 0) {
            //             obj.liveObj = response.data;
            //             $scope.detailedJSON.forEach(function (item, index) {
            //                 if (item.chid == obj.chid) {
            //                     $scope.detailedJSON[index].content.forEach(function (item2, index2) {
            //                         if (obj.CSID == item2.CSID) {
            //                             //delete obj.chid;//去除无用属性
            //                             $scope.detailedJSON[index].content.splice(index2, 1, obj);
            //                             return;
            //                         }
            //                     });
            //                 }
            //             });
            //             $scope.ke_system = false;

            //         } else {
            //             Msg.error("直播创建失败！");
            //         }
            //         $scope.islivebtnload = false;
            //     }, function () {
            //         Msg.error("直播创建失败！");
            //         $scope.islivebtnload = false;
            //     });

            //     return;
            // }

            //***************************************************************************************************
            $scope.detailedJSON.forEach(function (item, index) {
                if (item.chid == obj.chid) {
                    $scope.detailedJSON[index].content.forEach(function (item2, index2) {
                        if (obj.CSID == item2.CSID) {
                            //delete obj.chid;//去除无用属性
                            $scope.detailedJSON[index].content.splice(index2, 1, obj);
                            return;
                        }
                    });
                }
            });
            $scope.courseToast("【小节调整】");
        }
        $scope.ke_system = false;

    }
    //激活直播
    $scope.liveLive = function (item) {
        RS.openOrCloseLiveApi({ liveid: item.liveObj.liveid, status: "start", meetingNumber: item.liveObj.meetingNumber, password: item.PWD }).then(function (response) {
            if (response.errorcode == 0) {
                Msg.success("直播激活成功！");
            } else {
                if (response.errormsg.length > 0) {
                    var data = JSON.parse(response.errormsg);
                    if (data.errorCode == "60036") {
                        Msg.warning("请先预约-入会直播！");
                    } else {
                        Msg.error("直播激活失败！");
                    }
                } else {
                    Msg.error("直播激活失败！");
                }
            }
        });
    }
    $scope.LiveUserUrlFun = function () {
        $scope.liveuname = encodeURI(encodeURI(sysUserInfo.getuserinfo().username));
        $scope.liveuid = sysUserInfo.getuserinfo().user_ID;
        //console.log($scope.liveuname);
        return "uname=" + $scope.liveuname + "&uid=" + $scope.liveuid;
    }
    //直播超出时间 显示查看直播录像
    $scope.LiveTimeOut = function (time) {
        if (time == undefined) { return }
        var myDate = new Date(); //获取系统当前时间
        var usersysdate = myDate.getFullYear() + "-" + parseInt(myDate.getMonth() + 1) + "-" + myDate.getDate() + " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
        var livetimeout = GetDateDiff(time, usersysdate, "hour");
        if (livetimeout >= 4) {
            return false;
        } else {
            return true;
        }

    }


    //清除设置
    $scope.shezhiclear = function (obj) {
        //清除属性

        // var linshi =  angular.copy(obj);
        delete obj.CSTYPE;
        delete obj.stypeicon;
        delete obj.stypename;
        delete obj.CSDESCRIBE;
        delete obj.CSURL;
        delete obj.userObj;
        $scope.detailedJSON.forEach(function (item, index) {
            if (item.chid == obj.chid) {
                $scope.detailedJSON[index].content.forEach(function (item2, index2) {
                    if (obj.CSID == item2.CSID) {
                        delete obj.chid; //去除无用属性
                        $scope.detailedJSON[index].content.splice(index2, 1, obj);
                        return;
                    }
                });
            }
        });
        $scope.ke_system = false;
    }
    //修改类型    
    $scope.gaitype = function (typeitemid, flag) {
        // 2017-10-17 修改
        if (flag) {
            delete $scope.kechengtype.CSURL;
            delete $scope.kechengtype.CSTIME;
            delete $scope.kechengtype.CSURLNAME;
            delete $scope.kechengtype.chapterJson;
            delete $scope.kechengtype.userObj;
            $scope.knowConfig.ksfList = []; // 文件列表
        }
        $scope.kechengtype.CSTYPE = typeitemid;
        //直播类型，初始一下直播模式
        if (typeitemid == "6" || typeitemid == 6) {
            $scope.kechengtype.livetype = "2";
        }

        $scope.typelist.forEach(function (item, index) {
            item.sel = false;
            if (typeitemid == item.typeid) {
                item.sel = true;
                $scope.kechengtype.stypeicon = item.typeicon;
                $scope.kechengtype.stypename = item.typename;
            }
        });
    }

    // 线下课程时间变化。
    $scope.GetDate = function (item, index) {
        if (index == 1) {
            item.CSSTIME = document.getElementById("zb_CsTime").value;
        } else {
            item.CSETIME = document.getElementById("zb_CsEndTime").value;
        }
        console.log(item);
    }

    //删除章节
    $scope.delchapt = function (chinfo) {
        $scope.courseToast("【删除章节】", true).then(function (flag) {   // 删除弹框
            if (flag) {
                $scope.detailedJSON.forEach(function (item, index) {
                    if (item.chid == chinfo.chid) {
                        $scope.detailedJSON.splice(index, 1);
                    }
                });
            }
        });
    }


    //自动生成编号
    $scope.getnewid = function () {
        //        var guid = new GUID();        
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + "" + month + "" + strDate + "" + date.getHours() + "" + date.getMinutes() + "" + date.getSeconds() + date.getMilliseconds();
        return currentdate;
    }



    //各种类型的小节管理选项
    $scope.sectionManage = function (secinfo) {
        if (secinfo.CSTYPE == 1) {
            if (secinfo.manage_video) { secinfo.manage_video = false; } else { secinfo.manage_video = true; }
        } else if (secinfo.CSTYPE == 2) {
            if (secinfo.manage_file) { secinfo.manage_file = false; } else { secinfo.manage_file = true; }
        } else if (secinfo.CSTYPE == 6) {
            if (secinfo.manage_live) { secinfo.manage_live = false; } else { secinfo.manage_live = true; }
        } else if (secinfo.CSTYPE == 4) {
            if (secinfo.manage_offline) { secinfo.manage_offline = false; } else { secinfo.manage_offline = true; }
        } else if (secinfo.CSTYPE == 5) {
            if (secinfo.manage_ques) { secinfo.manage_ques = false; } else { secinfo.manage_ques = true; }
        } else if (secinfo.CSTYPE == 3) {
            if (secinfo.manage_exam) { secinfo.manage_exam = false; } else { secinfo.manage_exam = true; }
        } else if (secinfo.CSTYPE == 8) {
            if (secinfo.manage_imgtext) { secinfo.manage_imgtext = false; } else { secinfo.manage_imgtext = true; }
        } else {

        }
    }

    //关闭小节管理
    $scope.ishidefun = function () {
        //secinfo = { "secinfo": false, "manage_file": false, "manage_live": false, "manage_offline": false, "manage_ques": false, "manage_exam": false };
    }

    $scope.blurchname = function (chinfo, zjID) {
        //        console.log("input失焦_章节名称！");
        if (chinfo != undefined) {
            chinfo.chshow = false;

            //如果没有填写信息，就移出掉
            if (chinfo.CSNAME == "" || chinfo.CSNAME == undefined) {
                //$scope.delxiaojei(zjID, chinfo.CSID, 1);
                chinfo.CSNAME = "小节名称";
            } else {
                $scope.courseToast("【小节调整】");
            }
        }

    }

    $scope.editchname = function (chinfo) {
        //        console.log("input编辑_章节名称！");
        //未有人学习，可编辑
        if ($scope.studyCount <= 0) {
            if (chinfo.CSNAME == "小节名称") {
                chinfo.CSNAME = "";
            }
            chinfo.chshow = true;
        }
    }




    //图文类型  附文本编辑器相关处理和配置
    $scope.uuid = $scope.getnewid();

    $scope.configbtnjishiben = ['undo', 'redo', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', '|', 'quote', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright', '|', 'img', 'insertcode', ];

    $scope.courinfo_op = function (secinfo) {
        //存在风险
        //如果在纯文本框修改内容，在富文本框内容不会被修改
        $scope.kechengtype = secinfo;
        if (!$scope.kechengtype.hasOwnProperty("fileTxt")) {

            $scope.kechengtype.fileTxt = "";
        }

        $scope.courinfoManage(secinfo.CSTYPE);
    }



    //显示或者隐藏各种类型选择文件
    $scope.courinfoManage = function (cstype) {
        if (cstype == 1) {
            if ($scope.courcontent.courcontent_video) {
                $scope.courcontent.courcontent_video = false;
            } else {
                $scope.courcontent.courcontent_video = true;
            }
        } else if (cstype == 2) {
            if ($scope.courcontent.courcontent_file) { $scope.courcontent.courcontent_file = false; } else { $scope.courcontent.courcontent_file = true; }
        } else if (cstype == 6) {
            if ($scope.courcontent.courcontent_live) { $scope.courcontent.courcontent_live = false; } else { $scope.courcontent.courcontent_live = true; }
        } else if (cstype == 4) {
            if ($scope.courcontent.courcontent_offline) { $scope.courcontent.courcontent_offline = false; } else { $scope.courcontent.courcontent_offline = true; }
        } else if (cstype == 5) {
            if ($scope.courcontent.courcontent_ques) { $scope.courcontent.courcontent_ques = false; } else { $scope.courcontent.courcontent_ques = true; }
        } else if (cstype == 3) {
            if ($scope.courcontent.courcontent_exam) { $scope.courcontent.courcontent_exam = false; } else { $scope.courcontent.courcontent_exam = true; }
        } else if (cstype == 10) {
            if ($scope.courcontent.courcontent_more) { $scope.courcontent.courcontent_more = false; } else { $scope.courcontent.courcontent_more = true; }
        }
        else if (cstype == 9) {
            if ($scope.courcontent.courcontent_covert) {
                $scope.courcontent.courcontent_covert = false;
            } else {
                $scope.courcontent.courcontent_covert = true;
                //封面图片合成地址
                $scope.someUrl = $sce.trustAsResourceUrl("http://123.57.255.51:8088/Default.aspx?courseTitle=" + encodeURI($scope.traininfo.courseName) + "&courseDescribe=" + encodeURI($scope.traininfo.courseDetailed) + "&teacherName=" + encodeURI($scope.traininfo.lecturer) + "&callbackURL=http://123.57.255.51:8088/Ajax/SaveImg.ashx");
            }
        } else if (cstype == 8) {
            if ($scope.courcontent.courcontent_imgtext) { $scope.courcontent.courcontent_imgtext = false; } else {
                $scope.courcontent.courcontent_imgtext = true;
                //                if ($scope.secinfo.fileTxt != "" && $scope.secinfo.fileTxt != null) {
                //                    $scope.secinfo.fileTxt = decodeURIComponent($scope.secinfo.fileTxt);
                //                }
            }
        } else {

        }
    }

    //保存附文本编辑器内容
    $scope.savenotepad = function () {
        if ($scope.kechengtype.fileTxt == "" || $scope.kechengtype.fileTxt == null) {
            Msg.info("添加内容不能为空！");
            return;
        }
        //默认标题
        if (!$scope.kechengtype.CSTITLE || $scope.kechengtype.CSTITLE.length <= 0) {
            $scope.kechengtype.CSTITLE = delHtmlTag($scope.kechengtype.fileTxt).substring(0, 12);
        }
        //$scope.kechengtype.CSTITLE = delHtmlTag($scope.kechengtype.fileTxt);
        //$scope.kechengtype.fileTxt = base64encode($scope.kechengtype.fileTxt)
        // $scope.kechengtype.fileTxt = encodeURI(encodeURI($scope.kechengtype.fileTxt));
        //        $scope.secinfo.fileTxt = encodeURIComponent($scope.secinfo.fileTxt);
        //        $scope.isbtnload = true;
        $scope.courinfoManage(8);
    }

    //去掉所有的html标记
    function delHtmlTag(str) {
        if (str != undefined && str != null && str != "") {
            return str.replace(/<[^>]+>/g, "");
        } else {
            return "";
        }
    }

    //保存课件
    $scope.savetrain = function () {
        if ($scope.isbtnload)
            return;

        if ($scope.knowConfig.kssList.length <= 0) {
            Msg.warning("请选择课程分类！");
            return;
        }
        if ($scope.detailedJSON.length <= 0 || ($scope.detailedJSON.length == 1 && $scope.detailedJSON[0].content.length <= 0)) {
            Msg.warning("请至少添加一个小节！");
            return;
        }
        //        console.log(JSON.stringify($scope.traininfo)); //章节集合
        //        if ($scope.knowConfig.kssList.length <= 0) {
        //            Msg.info("课程分类不能为空！");
        //            return;
        //        }

        if ($scope.traininfo.isOpen == undefined) { $scope.traininfo.isOpen = "0"; }
        if ($scope.traininfo.courseOrder == undefined) { $scope.traininfo.courseOrder = "0"; }
        //sectionNum // 小节数
        //courseSum // 章节数
        $scope.traininfo.sectionNum = 0; //初始化小节数
        angular.forEach($scope.detailedJSON, function (data, index, array) {
            try {

                if (data.content != undefined && data.content != "" && data.content != null) {
                    //判断视频地址是否为手动录入，视频地址CSURL和视频名称CSURLNAME同值
                    angular.forEach(data.content, function (data2, index2, array2) {
                        if (data2.CSURL == undefined || data2.CSURL == "" || data2.CSURL == null) {
                            data2.CSURL = data2.CSURLNAME;
                        }
                        for (var i = index2 + 1; i < data.content.length - 1; i++) {
                            if (data.content[i].CSID == data2.CSID) {
                                data.content[i].CSID = $scope.getnewid() + i;
                            }
                        }
                        try {
                            // 处理存在小节脚本的信息
                            if (data2.hasOwnProperty("SCRIPTCONTENT") && data2.SCRIPTCONTENT) {
                                var dataScript = angular.copy(data2.SCRIPTCONTENT);
                                for (var i = 0; i < dataScript.length; i++) {
                                    // 多余的参数去掉
                                    delete dataScript[i].flag;
                                    // 小到大排序
                                    for (var m = i + 1; m < dataScript.length; m++) {
                                        if (dataScript[i].time > dataScript[m].time) {
                                            var zflag = dataScript[i];
                                            dataScript[i] = dataScript[m];
                                            dataScript[m] = zflag;
                                        }
                                    }
                                    // 没有内容的选项去掉
                                    if (dataScript[i].type == 1) {
                                        try {
                                            for (var k = 0; k < dataScript[i].contents.length; k++) {
                                                for (var j = 0; j < dataScript[i].contents.length; j++) {
                                                    if (!dataScript[i].contents[j].text) {
                                                        dataScript[i].contents.splice(j, 1);
                                                        break;
                                                    }
                                                }
                                            }
                                        } catch (e) { }
                                    }
                                }
                                data2.SCRIPTCONTENT = dataScript;
                            }
                        } catch (e) { }
                    });
                }
                $scope.traininfo.sectionNum += data.content.length;
            } catch (e) {
                $scope.traininfo.sectionNum += 0;
            }
        });
        $scope.traininfo.detailedJSON = [$scope.detailedJSON];
        // 章节数
        $scope.traininfo.courseSum = $scope.detailedJSON.length;
        //sendFlag false string 0更新课程不通知 1通知(预留)*
        $scope.traininfo.orgid = sysUserInfo.getuserinfo().organization_ID;
        $scope.traininfo.orgname = sysUserInfo.getuserinfo().organization_Name;
        $scope.traininfo.userid = sysUserInfo.getuserinfo().user_ID;
        $scope.traininfo.username = sysUserInfo.getuserinfo().username;
        $scope.traininfo.amountJSON = JSON.stringify([$scope.amountJSON]);
        //isOpen false string 是否公开
        //courseOrder false string 是否强制
        //coursePrice false string 课程价格
        //knowledgeId true string 知识架构id（如果有多个以，分隔）


        if ($scope.traininfo.courseName == undefined || $scope.traininfo.courseName == null || $scope.traininfo.courseName == "" || $scope.traininfo.courseName.length <= 0) {
            Msg.info("课程名称不能为空！");
            return;
        }

        if ($scope.knowConfig.kssList != undefined && $scope.knowConfig.kssList.length > 0) {
            $scope.traininfo.knowledgeJSON = JSON.stringify($scope.knowConfig.kssList);
            var kids = "";
            for (var i = 0; i < $scope.knowConfig.kssList.length; i++) {
                if (kids == "") {
                    kids = $scope.knowConfig.kssList[i].knowledge_Id;
                } else {
                    kids += "," + $scope.knowConfig.kssList[i].knowledge_Id;
                }
            }
            $scope.traininfo.knowledgeId = kids;
        }
        $scope.isbtnload = true;
        //保存课件
        $scope.traininfo.detailedJSON = base64encode(encodeURI(JSON.stringify($scope.traininfo.detailedJSON[0])));


        var id = "";
        //负责人id
        $scope.personDataUser.UserList.forEach(function (data, index) {
            id += (id.length > 0 ? ',' : '') + data.user_ID;
        });
        $scope.traininfo.relationId = id;

        // $scope.traininfo.detailedJSON = encodeURI(encodeURI(JSON.stringify($scope.traininfo.detailedJSON[0])));
        RS.AddNoCourseinfo($scope.traininfo).then(function (datashare) {
            $scope.isbtnload = false;
            if (datashare.errorcode == "0") {
                if ($scope.QuestionaireObj != null && $scope.QuestionaireObj.questionnaireId != undefined) {
                    RS.AssessRelation({ qid: $scope.QuestionaireObj.questionnaireId, userid: sysUserInfo.getuserinfo().user_ID, xtype: 2, xid: datashare.data.course_Id }).then(function (data) {
                        if (data.errorcode == 0) {
                            console.log("问卷添加成功！");
                        }
                    });
                }
                $state.go("index.Train.course", { index: $stateParams.index, screenText: $stateParams.screenText, knowledgeId: $stateParams.knowledgeId }, { reload: true });
            }else if(datashare.errorcode == "25") {
                 Msg.warning("直播次数不足，请充值！");
            } else {
                Msg.error("保存失败！");
            }
        }, function () { $scope.isbtnload = false; });
    }

    //提示框对应的显示隐藏控制
    $scope.coursMsg = { "coursinfo": false, "coursmore": false, "courschapter": false, "coursenotice": false, "cusoremore": false, "cusoreorder": false };
    //提示框显示
    $scope.showMsg = function (msgtype) {
        if (msgtype == 1) { $scope.coursMsg.coursinfo = true; }
        if (msgtype == 2) { $scope.coursMsg.coursmore = true; }
        if (msgtype == 3) { $scope.coursMsg.courschapter = true; }
        if (msgtype == 4) { $scope.coursMsg.coursenotice = true; }
        if (msgtype == 5) { $scope.coursMsg.cusoreorder = true; }

    }

    //提示框隐藏
    $scope.hideMsg = function (msgtype) {
        if (msgtype == 1) { $scope.coursMsg.coursinfo = false; }
        if (msgtype == 2) { $scope.coursMsg.coursmore = false; }
        if (msgtype == 3) { $scope.coursMsg.courschapter = false; }
        if (msgtype == 4) { $scope.coursMsg.coursenotice = false; }
        if (msgtype == 5) { $scope.coursMsg.cusoreorder = false; }
    }



    $scope.isupobj = { "upflag": false, "isbtn": false, "datas": [] };   // 初始化    
    $scope.isupflagfun = function () {//点击查看传输列表
        $scope.isupobj.isbtn = true; // 标志按扭点击的
        $scope.isupobj.upflag = !$scope.isupobj.upflag;
        if ($scope.isupobj.upflag) {    // 向服务器拿数据 放这边会重置datas所以放初始化       
            //            then(function (data) {
            //                $scope.isupobj.datas = data;
            //            }, function callback() { });
        }
    }

    /*********************************************文件上传开始**********************************************/

    var trainupfile = $scope.isupobj.datas = $scope.uploader = new FileUploader();
    trainupfile.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {     // 选择文件后失败       0
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    trainupfile.onAfterAddingFile = function (fileItem) {  // 选择文件后 （成功）   0          
        console.info('onAfterAddingFile', fileItem);
        if (trainupfile.isUploading) {
            MsgCon.alert("有文件正在上传。。");
            return;
        } else {
            var upfileparam = "?fid=0&fpath=/&orgid=" + sysUserInfo.getuserinfo().organization_ID + "&userid=" + sysUserInfo.getuserinfo().user_ID + "&username=" + sysUserInfo.getuserinfo().username;
            //上传文件路径
            fileItem.url = RS.uploadCover(upfileparam);
        }
    };
    trainupfile.onAfterAddingAll = function (addedFileItems) { // 选择文件后添加到队列   1 
        console.info('onAfterAddingAll', addedFileItems);
        if (trainupfile.isUploading) {
            MsgCon.alert("有文件正在上传。。");
            return;
        } else {
            $scope.isupobj.upflag = true;
            $scope.isupobj.isbtn = true;  // 初始化   
            trainupfile.uploadAll();
        }
    };
    // 开始上传
    trainupfile.onBeforeUploadItem = function (item) {    // 2 上传之前一项
        console.info('onBeforeUploadItem', item);
        item.file.pid = 0;
    };
    trainupfile.onProgressItem = function (fileItem, progress) {   // 3 上传进度
        console.info('onProgressItem', fileItem, progress);
    };
    trainupfile.onProgressAll = function (progress) {      //4 队列进度
        console.info('onProgressAll', progress);
    };
    trainupfile.onSuccessItem = function (fileItem, response, status, headers) {   // 5上传成功
        console.info('onSuccessItem', fileItem, response, status, headers); //fileItem 请求信息 response: 返回值status: 返回状态  headers: 请求头 
        fileItem.resdata = response; //临时的
        if (response.errorcode == "0") {
            Msg.success("文件上传成功！")
            if (response.errormsg != undefined) {
                //                console.log(response.data);
                fileItem.resdata = response.errormsg;  // 文件对象的信息        
                //                $scope.traininfo.courseImg = response.data.filepreview;
                $scope.traininfo.courseImg = response.errormsg;

            }
        } else if (response.errorcode == "30") {// 上传地址有问题
            Msg.info("文件上传成功，已存入同名文件的历史记录中！")
        } else if (response.errorcode == "33") {// 转换失败
            Msg.error("文件上传成功，文件转码失败！")
            if (response.data != undefined) {
                //                console.log(response.data);
                fileItem.resdata = response.errormsg;  // 文件对象的信息
            }
        } else {
            Msg.error("文件上传异常！")
        }
    };
    trainupfile.onErrorItem = function (fileItem, response, status, headers) {     // 5上传失败
        console.info('onErrorItem', fileItem, response, status, headers);
        //        $scope.exUserList[0].import_State = "失败";
        //        MsgCon.alert("连接不上服务器");
        //trainupfile.clearQueue();
    };
    trainupfile.onCancelItem = function (fileItem, response, status, headers) {    //5取消上传
        //$scope.exUserList[0].import_State = "取消";
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    trainupfile.onCompleteItem = function (fileItem, response, status, headers) {  //6     单文件上传完成
        console.info('onCompleteItem', fileItem, response, status, headers);

    };
    trainupfile.onCompleteAll = function () {  // 6 单文件上传完成或者队列上传完成的时候
        console.info('onCompleteAll');
        //trainupfile.clearQueue();  // 上传完毕清除队列
    };
    /*********************************************文件上传结束**********************************************/

    //         $scope.knowConfig = {   // 配置知识选择器的参数
    //                 menu:[], //["folder","file","courseware","structure","examination"],
    //                 windowSize:"standard", //  窗口类型 standard:标准(默认)  mini :迷你
    //                 kssMore:false, //知识结构 是否多选
    //                 kssList:[],    // 知识结构选中列表
    //                 kscMore:false, // 课程列表是否多选
    //                 kscList:[], // 课程选中列表
    //                 kseMore:true, // 试卷列表是否多选
    //                 kseList:[], // 试卷选中列表
    //                 ksfMore:true, //文件是否多选
    //                 ksfList:[], // 文件列表
    //                 ksfType:0, // 文件类型 默认空  0 全部  1 文档 2 视频
    //                 ksmMore:true, // 文件夹 是否多选
    //                 ksmList:[],    // 文件夹列表
    //                 isShow:false,  // 显示知识选择器
    //                 secinfo:""
    //             };       
    //    配置知识选择器
    $scope.knowConfig = {   // 配置知识选择器的参数
        menu: ["structure"],
        kssMore: true, //知识结构 是否多选
        kssList: [],    // 知识结构选中列表               
        qunaireMore: false,  // 问卷列表是否多选
        qunaireList: [], // 问卷选中列表  
        isShow: false  // 显示知识选择器
    };

    //更改课件封面图片
    $scope.updimgsrc = function (imgtype) {
        if (imgtype == 1) {
            $scope.traininfo.courseImg = "/images/train/fengmian001.gif";
        } else if (imgtype == 2) {
            $scope.traininfo.courseImg = "/images/train/fengmian002.gif";
        } else {
            $scope.traininfo.courseImg = imgtype;
        }
    }

    //删除课程分类
    $scope.delknowinfo = function (kssinfo) {
        $scope.knowConfig.kssList.forEach(function (item, index) {
            if (kssinfo.knowledge_Id == item.knowledge_Id) {
                $scope.knowConfig.kssList.splice(index, 1);
                return;
            }
        });
    }

    // 打开知识选择器（课程分类）
    $scope.modifyOrder = function () {
        if ($scope.knowConfig.isShow) {
            $scope.knowConfig.isShow = false;
        } else {
            $scope.knowConfig.menu = ["structure"];
            $scope.knowConfig.kssMore = true;
            $scope.knowConfig.isShow = true;
            if ($scope.knowConfig.kssList == null || $scope.knowConfig.kssList == undefined || $scope.knowConfig.kssList == "" || $scope.knowConfig.kssList.length <= 0) {
                $scope.knowConfig.kssList = [];
            }
            //console.log($scope.knowConfig);
        }
    }

    $scope.knowChapter = {   // 配置知识选择器的参数
        menu: [], //["folder","file","courseware","structure","examination"],
        windowSize: "standard", //  窗口类型 standard:标准(默认)  mini :迷你
        kssMore: false, //知识结构 是否多选
        kssList: [],    // 知识结构选中列表
        kscMore: false, // 课程列表是否多选
        kscList: [], // 课程选中列表
        kseMore: false, // 试卷列表是否多选
        kseList: [], // 试卷选中列表
        ksfMore: false, //文件是否多选
        ksfList: [], // 文件列表
        ksfType: 0, // 文件类型 默认空  0 全部  1 文档 2 视频
        ksmMore: false, // 文件夹 是否多选
        ksmList: [],    // 文件夹列表
        isShow: false,  // 显示知识选择器
        secinfo: ""
    };
    $scope.$watch('knowChapter.isShow', function (newV, oldV, scope) {
        // 只是针对一个监听  如果是页面用的情况下直接引用字段就可以了现在要传两层
        if (!$scope.knowChapter.isShow && newV != oldV) {
            // 2017-10-17 修改
            newV = $scope.knowChapter;
            if ($scope.knowChapter.secinfo.CSTYPE == 5) {//知识结构
                if (newV.kssList.length > 0) {
                    $scope.knowChapter.secinfo.chapterJson = JSON.stringify(newV.kssList);
                } else {
                    $scope.knowChapter.secinfo.chapterJson = "";
                }
                if (newV.kssList.length > 0) {
                    var knowName = [];
                    for (var i = 0; i < newV.kssList.length; i++) {
                        knowName.push(newV.kssList[i].knowledge_Name);
                    }
                    $scope.knowChapter.secinfo.CSURL = knowName.join(",");
                }
            } else if ($scope.knowChapter.secinfo.CSTYPE == 1 || $scope.knowChapter.secinfo.CSTYPE == 2) {
                //选择器选择了文件或视频
                if (newV.ksfList.length > 0) {
                    if ($scope.isVideoDocFlag) {
                        $scope.knowChapter.secinfo.docChapterJson = JSON.stringify(newV.ksfList);
                    } else {
                        $scope.knowChapter.secinfo.chapterJson = JSON.stringify(newV.ksfList);
                    }
                } else {
                    if ($scope.isVideoDocFlag) {
                        $scope.knowChapter.secinfo.docChapterJson = "";
                    } else {
                        $scope.knowChapter.secinfo.chapterJson = "";
                    }
                }
                if (newV.ksfList.length > 0) {
                    for (var i = 0; i < newV.ksfList.length; i++) {
                        if ($scope.isVideoDocFlag) {
                            $scope.knowChapter.secinfo.CSFILEDOCID = newV.ksfList[i].upId;
                            $scope.knowChapter.secinfo.CSDOCURL = newV.ksfList[i].filepreview;
                        } else {
                            //将第一个文件绑定到现有对象上
                            //第二个文件，新建一个对象，则自动追加到列表后面                       
                            if (i == 0) {
                                //更新
                                //视频地址
                                $scope.knowChapter.secinfo.CSURL = newV.ksfList[i].filepreview;
                                // 文件id
                                $scope.knowChapter.secinfo.CSFILEID = newV.ksfList[i].upId;
                                //视频名称
                                //如果，还未设置小节名称，则直接创建
                                //$scope.knowChapter.secinfo.CSURLNAME = fileName.join(","); 
                                if ($scope.knowChapter.secinfo.CSNAME == "小节名称") {
                                    var file_name = newV.ksfList[i].fileName;
                                    // 去除扩展名                               
                                    $scope.knowChapter.secinfo.CSNAME = file_name.lastIndexOf('.') != -1 ? file_name.substr(0, file_name.lastIndexOf('.')) : file_name;
                                }
                                $scope.knowChapter.secinfo.CSURLNAME = newV.ksfList[i].filepreview;

                                if ($scope.knowChapter.secinfo.CSURL == undefined || $scope.knowChapter.secinfo.CSURL == "" || $scope.knowChapter.secinfo.CSURL == null) {
                                    $scope.knowChapter.secinfo.CSURL = $scope.knowChapter.secinfo.CSURLNAME;
                                }
                                if (newV.ksfList[i].videotime != undefined && newV.ksfList[i].videotime != null && newV.ksfList[i].videotime != "") {
                                    $scope.knowChapter.secinfo.CSTIME = parseInt(newV.ksfList[i].videotime / 60);
                                    if (parseInt($scope.knowChapter.secinfo.CSTIME) <= 0) {
                                        $scope.knowChapter.secinfo.CSTIME = 1;
                                    }
                                }
                            }
                            else {
                                //新建

                                var youle = false;
                                //确认这个没有增加过
                                var dl = $scope.detailedJSON.length;
                                $scope.detailedJSON[dl - 1].content.forEach(function (item, index) {
                                    if (item.CSURL == newV.ksfList[i].filepreview) {
                                        youle = true;
                                        return; //如果已经有了，就不追加了
                                    }
                                });

                                if (!youle) {
                                    Msg.info("已经为您自动追加：《" + newV.ksfList[i].fileName + "》");
                                    var file_name = newV.ksfList[i].fileName;
                                    var newkecheng = { "CSID": $scope.getnewid() + i,
                                        "CSNAME": file_name.lastIndexOf('.') != -1 ? file_name.substr(0, file_name.lastIndexOf('.')) : file_name,
                                        "CSTYPE": $scope.knowChapter.secinfo.CSTYPE,
                                        "CSURL": newV.ksfList[i].filepreview,
                                        "CSURLNAME": newV.ksfList[i].filepreview,
                                        "CSTIME": (newV.ksfList[i].videotime != undefined && newV.ksfList[i].videotime != null && newV.ksfList[i].videotime != "" && parseInt(newV.ksfList[i].videotime) > 0) ? parseInt(newV.ksfList[i].videotime / 60) : 1,
                                        "stypeicon": $scope.knowChapter.secinfo.stypeicon,
                                        "stypename": $scope.knowChapter.secinfo.stypename,
                                        "chshow": true,
                                        "CSFILEID": newV.ksfList[i].upId,
                                        "CSPNUM": 0,
                                        "PWD": "",
                                        "liveObj": ""
                                    };
                                    //插入最后一个章节中
                                    $scope.detailedJSON[$scope.detailedJSON.length - 1].content.push(newkecheng);
                                }

                            }

                        }
                    }
                } else {
                    Msg.warning("请留意", "没有进行任何文件选择，创建了一个默认的空小节。");
                }
                $scope.isVideoDocFlag = false;
            } else if ($scope.knowChapter.secinfo.CSTYPE == 3) {
                if (newV.kseList.length > 0) {
                    $scope.knowChapter.secinfo.chapterJson = JSON.stringify(newV.kseList);
                    $scope.knowChapter.secinfo.CSSCORE = newV.kseList[0].passGrade;
                    $scope.knowChapter.secinfo.CSFULLSCORE = newV.kseList[0].totalScore;
                    $scope.knowChapter.secinfo.CSPID = newV.kseList[0].paperId;
                    $scope.knowChapter.secinfo.CRANDIM = newV.kseList[0].paper_Random;
                    $scope.knowChapter.secinfo.CSPCOUNT = newV.kseList[0].paperCount;
                } else {
                    $scope.knowChapter.secinfo.chapterJson = "";
                }
                if (newV.kseList.length > 0) {
                    var paperName = [];
                    for (var i = 0; i < newV.kseList.length; i++) {
                        paperName.push(newV.kseList[i].paperName);
                    }
                    $scope.knowChapter.secinfo.CSURL = paperName.join(",");
                }
                //向最后一个章节添加
                if (newV.kseList[0].question_Count == "0" || newV.kseList[0].question_Count == 0 || newV.kseList[0].question_Count == undefined) {
                    Msg.info("选择的试卷没有试题，请重新选择！");
                }
            }
        }
        scope.kssList = newV.kssList;
    }, true);
    // 脚本 start
    $scope.scriptObj = {
        obj: {},
        isShow: false
    }
    // 验证是不是mp4 文件 确定要不要加入脚本
    $scope.isMp4 = function (obj) {
        if (obj && obj.CSURLNAME) {
            if (obj.CSURLNAME.substring(obj.CSURLNAME.lastIndexOf(".")).indexOf(".mp4") >= 0) {
                return true;
            } else {
                return false;
            }
        }
    }
    // 打开脚本编辑
    $scope.openScript = function (obj) {
        //console.log(JSON.stringify(obj));
        $scope.scriptObj.obj = obj;
        $scope.scriptObj.isShow = true;
    }

    // 脚本 end    
    // 改动时删除fileid
    $scope.clearFileID = function (event, obj) {

        if(obj.hasOwnProperty("CSFILEID")){
            delete obj.CSFILEID;
            obj.CSURL = obj.CSURLNAME;
        }

        if (obj.CSDOCURL && obj.hasOwnProperty("CSFILEDOCID")) {
            delete obj.CSFILEDOCID;
        }

    }

    // 打开知识选择器（课程分类）
    $scope.opknowChapter = function (secinfo) {
        if ($scope.knowConfig.isShow) {
            $scope.knowConfig.isShow = false;
        } else {
            $scope.knowConfig.menu = ["structure"];
            $scope.knowConfig.secinfo = secinfo;
            $scope.knowConfig.isShow = true;
        }
    }
    // 视频中选择文档。
    $scope.isVideoDocFlag = false;
    $scope.openVideoDoc = function (secinfo) {
        $scope.isVideoDocFlag = true;
        $scope.openChapter(secinfo, false);
    }
    //多个模式选择器展现
    $scope.openChapter = function (secinfo, flag) {
        //console.log(secinfo);
        if (flag) {
            $scope.knowChapter.ksfMore = flag;
        } else {
            $scope.knowChapter.ksfMore = false;
            //secinfo.chapterJson = "";
        }
        if ($scope.knowChapter.isShow) {
            $scope.knowChapter.isShow = false;
        }
        else {
            $scope.knowChapter.secinfo = secinfo;
            $scope.knowChapter.isShow = true;
            $scope.knowChapter.kssList = [];
            $scope.knowChapter.ksfList = [];
            $scope.knowChapter.kseList = [];
            if (secinfo.CSTYPE == 1) {
                $scope.knowChapter.menu = ["file"];
                if ($scope.isVideoDocFlag) {
                    $scope.knowChapter.ksfType = 1; //文件选择模式
                    $scope.knowConfig.ksfList = []; // 文件列表
                    if (secinfo.docChapterJson == undefined || secinfo.docChapterJson == "" || secinfo.docChapterJson == "[]") {
                        $scope.knowConfig.ksfList = []; // 文件列表
                    } else {
                        $scope.knowChapter.ksfList = eval(secinfo.docChapterJson); // 编辑时用到时，预览时不用。可保存的时候删除
                    }
                } else {
                    $scope.knowChapter.ksfType = 2; //文件选择模式
                    $scope.knowConfig.ksfList = []; // 文件列表
                    if (secinfo.chapterJson == undefined || secinfo.chapterJson == "" || secinfo.chapterJson == "[]") {
                        $scope.knowConfig.ksfList = []; // 文件列表
                    } else {
                        $scope.knowChapter.ksfList = eval(secinfo.chapterJson);
                    }
                }

            } else if (secinfo.CSTYPE == 2) {
                $scope.knowChapter.menu = ["file"];
                $scope.knowChapter.ksfType = 1;
                $scope.knowChapter.ksfList = []; // 文件列表
                if (secinfo.chapterJson == undefined || secinfo.chapterJson == "" || secinfo.chapterJson == "[]") {
                    $scope.knowChapter.ksfList = []; // 文件列表
                } else {
                    $scope.knowChapter.ksfList = eval(secinfo.chapterJson);
                }
            } else if (secinfo.CSTYPE == 5) {
                $scope.knowChapter.menu = ["structure"];
                if (secinfo.chapterJson == undefined || secinfo.chapterJson == "" || secinfo.chapterJson == "[]") {
                    $scope.knowChapter.kssList = [];   // 知识结构选中列表       
                } else {
                    $scope.knowChapter.kssList = eval(secinfo.chapterJson);
                }
            } else if (secinfo.CSTYPE == 3) {
                $scope.knowChapter.menu = ["examination"];
                if (secinfo.chapterJson == undefined || secinfo.chapterJson == "" || secinfo.chapterJson == "[]") {
                    $scope.knowChapter.kseList = []; // 试卷选中列表
                } else {
                    $scope.knowChapter.kseList = eval(secinfo.chapterJson);
                }
            }
        }
    }

    //    console.log($stateParams.courid);
    //查询课程详细
    $scope.findCourseDetailed = function (trainid) {
        //查询课程里绑定的问卷
        RS.findBinding({ xid: trainid, xtype: 2 }).then(function (data) {
            if (data.errorcode == "0") {
                if (data.data != undefined && data.data != null) {
                    $scope.QuestionaireObj = data.data;
                }
            } else {
                Msg.error("获取问卷失败！");
            }
        });
        RS.findCourseDetailed({ courseId: trainid }).then(function (datashare) {
            if (datashare.errorcode == "0") {
                $scope.traininfo = datashare.datas[0];
                $scope.getPerson(); //查询负责人
                //初始化课程资料---{课程简介，课程资料}
                if ($scope.traininfo.courseDetailed != undefined && $scope.traininfo.courseDetailed != null && $scope.traininfo.courseDetailed.length > 0) {
                    //这里已经是新业务
                    try {
                        $scope.traininfo.courseDetailed = JSON.parse($scope.traininfo.courseDetailed);
                        //报错以后是老业务(需要做兼容)
                    } catch (e) {
                        var introduce = $scope.traininfo.courseDetailed;
                        $scope.traininfo.courseDetailed = { introduce: introduce, fileList: [] };
                    }
                } else {
                    $scope.traininfo.courseDetailed = { introduce: "", fileList: [] };
                }
                if ($scope.traininfo.coursePrice == undefined) {
                    $scope.traininfo.coursePrice = 0;
                }
                //初始积分
                if ($scope.traininfo.integral != undefined) {
                    $scope.traininfo.integral = parseInt($scope.traininfo.integral);
                } else {
                    $scope.traininfo.integral = 0;
                }

                if ($scope.traininfo.lecturer == undefined) { $scope.traininfo.lecturer = sysUserInfo.getuserinfo().username; }
                //章节
                if ($scope.traininfo.detailedJSON != "" && $scope.traininfo.detailedJSON != undefined) {

                    $scope.traininfo.detailedJSON = eval("(" + $scope.traininfo.detailedJSON + ")");
                    if ($scope.traininfo.detailedJSON.length > 0) {
                        $scope.traininfo.detailedJSON.forEach(function (item, index) {
                            $scope.traininfo.detailedJSON[index].content = eval(item.content);

                            $scope.traininfo.detailedJSON[index].content.forEach(function (item2, index2) {

                                if ($scope.traininfo.detailedJSON[index].content[index2].stypeicon == undefined) {
                                    if (item2.CSTYPE == 1) {
                                        $scope.traininfo.detailedJSON[index].content[index2].stypeicon = "&#xe73b;";
                                        $scope.traininfo.detailedJSON[index].content[index2].stypename = "视频";
                                    } else if (item2.CSTYPE == 2) {
                                        $scope.traininfo.detailedJSON[index].content[index2].stypeicon = "&#xe731;";
                                        $scope.traininfo.detailedJSON[index].content[index2].stypename = "文档";
                                    } else if (item2.CSTYPE == 3) {
                                        $scope.traininfo.detailedJSON[index].content[index2].stypeicon = "&#xe62a;";
                                        $scope.traininfo.detailedJSON[index].content[index2].stypename = "题库";
                                    }
                                }

                            });
                        });
                    }
                    $scope.detailedJSON = $scope.traininfo.detailedJSON;
                }
                //
                if ($scope.traininfo.knowledgeJSON != "" && $scope.traininfo.knowledgeJSON != undefined) {
                    $scope.traininfo.knowledgeJSON = eval("(" + $scope.traininfo.knowledgeJSON + ")");
                    //                    $scope.knowConfig.kssList = $scope.traininfo.knowledgeJSON;
                }
                //
                if ($scope.traininfo.amountJSON != "" && $scope.traininfo.amountJSON != undefined) {
                    $scope.traininfo.amountJSON = eval("(" + $scope.traininfo.amountJSON + ")");
                    $scope.amountJSON = $scope.traininfo.amountJSON;
                }
                $scope.initAddChapter = false;
            } else {
                Msg.error("查询课程详细异常！")
            }
            // 测试使用     
            // $scope.openScript($scope.detailedJSON[0].content[0]);
        });
        //查询课程关联的知识架构
        RS.findKnowledgeByCourse({ courseId: trainid }).then(function (datashare) {
            //debugger;
            if (datashare.errorcode == "0") {
                $scope.knowConfig.kssList = datashare.datas;
            }
        });

    }

    //随机更换课件封面
    $scope.randomCoursImg = function () {
        $scope.rcoursimg = true;
        var imgNum = Math.round(Math.random() * 10);
        if ($scope.traininfo.courseImg == "/images/train/fengmian00" + imgNum + ".gif") {
            $scope.randomCoursImg();
        } else {
            $timeout(function () {
                $scope.traininfo.courseImg = "/images/train/fengmian00" + imgNum + ".gif";
                $scope.rcoursimg = false;
            }, 1500);
        }
    }

    //接收传参
    if ($stateParams.courid != "" && $stateParams.courid != "0") {
        $scope.findCourseDetailed($stateParams.courid);
    } else {
        if ($scope.traininfo.coursePrice != undefined) {
            $scope.traininfo.coursePrice = parseInt($scope.traininfo.coursePrice);
        }
        $scope.traininfo.courseImg = "/images/train/fengmian00" + Math.round(Math.random() * 7) + ".gif";
    }

    if ($scope.traininfo != "" && $scope.traininfo.detailedJSON != undefined && $scope.traininfo.detailedJSON.length > 0) {
        $scope.detailedJSON = $scope.traininfo.detailedJSON;
        $scope.initAddChapter = false;
    }

    //小节回车聚焦下一个文本框
    $scope.myKeyup = function (e, chinfo, secinfo) {
        var keycode = window.event ? e.keyCode : e.which;
        if (keycode == 13) {
            secinfo.chshow = false;
            $scope.courseToast("【小节调整】");
            $scope.AddSection(chinfo.chid);
        }
    }




    $scope.setopen = function (val) {
        $scope.traininfo.isOpen = val;
    }
    // guanbi
    $scope.closeAddEditCourse = function () {
        MsgCon.delnoicon("提示", "确认取消操作吗？", "", "确定", "继续").then(function (data) {
            if (data) {
                updateUrl.upUrl(-1);
                $state.go("index.Train.course");
            }
        });
    }
    /*
    CSID:"1136d3d4-777c-8cbd-c03f-5349dca25278"
    CSNAME:"文件名称"
    CSTIME:"11"
    CSTYPE:"1"
    CSURL:"http://uploadfilebucket.bj.bcebos.com/resources/knowledge/4e4f9eaf-d9bd-45b0-8ff7-30a9e9faa7a7/d299de6e-a920-4e3d-bce1-4d4f74fa1276/abaa09d6-53b9-4ab1-8ead-e81f14500ac8/中医内科学01.mp4"
    size:"0"


    CNAME:"kiuyhihiuo233"
    CRANDIM:"1"
    CSID:"1ee31efe-09a8-04a6-20ea-33b22aa1645e"
    CSNAME:"试卷名称"
    CSPCOUNT:"0"
    CSPID:"225352ae-08ca-4b45-acfb-c7ac0e2cb38c"
    CSSCORE:"10"
    CSTIME:"1"
    CSTYPE:"3"
    CSURL:"/resources/exam/225352ae-08ca-4b45-acfb-c7ac0e2cb38c/225352ae-08ca-4b45-acfb-c7ac0e2cb38c.html?scoreId=1&id=1"



    "[{"chapter":"章节名称","content":"[{\"CSID\":\"1136d3d4-777c-8cbd-c03f-5349dca25278\",\"CSNAME\":\"文件名称\",\"CSTYPE\":\"1\",\"CSURL\":\"http://uploadfilebucket.bj.bcebos.com/resources/knowledge/4e4f9eaf-d9bd-45b0-8ff7-30a9e9faa7a7/d299de6e-a920-4e3d-bce1-4d4f74fa1276/abaa09d6-53b9-4ab1-8ead-e81f14500ac8/中医内科学01.mp4\",\"CSTIME\":\"11\",\"size\":\"0\"},{\"CSID\":\"1ee31efe-09a8-04a6-20ea-33b22aa1645e\",\"CSNAME\":\"试卷名称\",\"CSTYPE\":\"3\",\"CNAME\":\"kiuyhihiuo233\",\"CSTIME\":\"1\",\"CSSCORE\":\"10\",\"CSPID\":\"225352ae-08ca-4b45-acfb-c7ac0e2cb38c\",\"CSPCOUNT\":\"0\",\"CSURL\":\"/resources/exam/225352ae-08ca-4b45-acfb-c7ac0e2cb38c/225352ae-08ca-4b45-acfb-c7ac0e2cb38c.html?scoreId=1&id=1\",\"CRANDIM\":\"1\"}]"}]"

    //封面合成
    http://123.57.255.51:8088/Default.aspx

    */
    String.prototype.MD5 = function (bit) {
        var sMessage = this;
        function RotateLeft(lValue, iShiftBits) { return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); }
        function AddUnsigned(lX, lY) {
            var lX4, lY4, lX8, lY8, lResult;
            lX8 = (lX & 0x80000000);
            lY8 = (lY & 0x80000000);
            lX4 = (lX & 0x40000000);
            lY4 = (lY & 0x40000000);
            lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
            if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
            if (lX4 | lY4) {
                if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
                else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            } else return (lResult ^ lX8 ^ lY8);
        }
        function F(x, y, z) { return (x & y) | ((~x) & z); }
        function G(x, y, z) { return (x & z) | (y & (~z)); }
        function H(x, y, z) { return (x ^ y ^ z); }
        function I(x, y, z) { return (y ^ (x | (~z))); }
        function FF(a, b, c, d, x, s, ac) {
            a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
            return AddUnsigned(RotateLeft(a, s), b);
        }
        function GG(a, b, c, d, x, s, ac) {
            a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
            return AddUnsigned(RotateLeft(a, s), b);
        }
        function HH(a, b, c, d, x, s, ac) {
            a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
            return AddUnsigned(RotateLeft(a, s), b);
        }
        function II(a, b, c, d, x, s, ac) {
            a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
            return AddUnsigned(RotateLeft(a, s), b);
        }
        function ConvertToWordArray(sMessage) {
            var lWordCount;
            var lMessageLength = sMessage.length;
            var lNumberOfWords_temp1 = lMessageLength + 8;
            var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
            var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
            var lWordArray = Array(lNumberOfWords - 1);
            var lBytePosition = 0;
            var lByteCount = 0;
            while (lByteCount < lMessageLength) {
                lWordCount = (lByteCount - (lByteCount % 4)) / 4;
                lBytePosition = (lByteCount % 4) * 8;
                lWordArray[lWordCount] = (lWordArray[lWordCount] | (sMessage.charCodeAt(lByteCount) << lBytePosition));
                lByteCount++;
            }
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
            lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
            lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
            return lWordArray;
        }
        function WordToHex(lValue) {
            var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
            for (lCount = 0; lCount <= 3; lCount++) {
                lByte = (lValue >>> (lCount * 8)) & 255;
                WordToHexValue_temp = "0" + lByte.toString(16);
                WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
            }
            return WordToHexValue;
        }
        var x = Array();
        var k, AA, BB, CC, DD, a, b, c, d
        var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
        var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
        var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
        var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
        // Steps 1 and 2. Append padding bits and length and convert to words 
        x = ConvertToWordArray(sMessage);
        // Step 3. Initialise 
        a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
        // Step 4. Process the message in 16-word blocks 
        for (k = 0; k < x.length; k += 16) {
            AA = a; BB = b; CC = c; DD = d;
            a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
            d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
            c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
            b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
            a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
            d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
            c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
            b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
            a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
            d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
            c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
            b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
            a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
            d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
            c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
            b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
            a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
            d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
            c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
            b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
            a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
            d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
            c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
            b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
            a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
            d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
            c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
            b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
            a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
            d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
            c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
            b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
            a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
            d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
            c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
            b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
            a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
            d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
            c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
            b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
            a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
            d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
            c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
            b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
            a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
            d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
            c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
            b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
            a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
            d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
            c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
            b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
            a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
            d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
            c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
            b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
            a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
            d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
            c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
            b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
            a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
            d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
            c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
            b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
            a = AddUnsigned(a, AA); b = AddUnsigned(b, BB); c = AddUnsigned(c, CC); d = AddUnsigned(d, DD);
        }
        if (bit == 32) {
            return WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
        }
        else {
            return WordToHex(b) + WordToHex(c);
        }
    }
    function GetDateDiff(startTime, endTime, diffType) {
        //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式  
        startTime = startTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        //将计算间隔类性字符转换为小写  
        diffType = diffType.toLowerCase();
        var sTime = new Date(startTime);      //开始时间  
        var eTime = new Date(endTime);  //结束时间  
        //作为除数的数字  
        var divNum = 1;
        switch (diffType) {
            case "second":
                divNum = 1000;
                break;
            case "minute":
                divNum = 1000 * 60;
                break;
            case "hour":
                divNum = 1000 * 3600;
                break;
            case "day":
                divNum = 1000 * 3600 * 24;
                break;
            default:
                break;
        }
        return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
    }
    /************************************************人员选择器******************************************************/
    $scope.mousePosition = function (ev) {
        if (!ev) {
            ev = window.event;
        }

        if (ev.type != "click") {
            return;
        }
        var width = 0;
        var height = 0;
        if (ev.pageX || ev.pageY) {//firefox、chrome等浏览器
            if (document.documentElement.clientWidth - ev.pageX < 450) {
                width = ev.pageX - (450 - (document.documentElement.clientWidth - ev.pageX)) - 20;
            } else {
                width = ev.pageX;
            }
            if (document.documentElement.clientHeight - ev.pageY < 480) {
                height = ev.pageY - (480 - (document.documentElement.clientHeight - ev.pageY)) - 20;
            } else {
                height = ev.pageY;
            }

            return { "left": width + "px", "top": height + "px", "position": "fixed" };
        }

        return {// IE浏览器
            "left": ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            "top": ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    }
    // 人员选择器
    //批量添加负责人 选择器初始化
    $scope.personData = {
        ApiOpen: false,
        style: "",
        menu: [{ "id": "User"}],
        UserList: [],
        searchType: [],  //初始化教师查询
        DB: "0",
        DBdata: []
    }
    $scope.$watch('personData.UserList', function (newValue, oldValue, scope) {
        if ($scope.personData.UserList.length > 0) {
            if ($scope.personData.UserList[0].powerLV == "99") {
                Msg.warning("学员不能开播，请重新选择！");
                $scope.personData.UserList = [];
                return;
            }
            $scope.kechengtype.userObj = $scope.personData.UserList[0];
            $scope.personData.ApiOpen = false;
        }
    }, true);

    //打开人员选择器
    $scope.openPensonle = function (event) {
        $scope.personData.style = $scope.mousePosition(event);
        $scope.personData.UserList = [];
        $scope.personData.ApiOpen = true;
    }
    /*****************************************************************************************************************/
    $scope.openUrl = "";
    //直播
    //type   1,开始直播，2查看回放
    $scope.playLive = function (section, type) {
        var open = window.open();

        if (section.liveObj.livetype == 3) {
            open.location = section.liveObj.teach_htm;
        } else {
            if (type == "2") {
                RS.getTiket({ username: sysUserInfo.getuserinfo().user_Name, userId: sysUserInfo.getuserinfo().user_ID, orgId: sysUserInfo.getuserinfo().organization_ID }).then(function (response) {
                    if (response.errorcode == "0") {
                        var data = JSON.parse(response.data);
                        if (data.state == "101") {
                            $scope.openUrl = section.liveObj.record_htm + "?ticket=" + data.ticket + "&uid=" + sysUserInfo.getuserinfo().user_ID + "&uname=" + encodeURI(encodeURI(sysUserInfo.getuserinfo().user_Name)) + "&img=" + encodeURI(encodeURI($rootScope.fileurl + "/resources/logo/" + sysUserInfo.getuserinfo().organization_ID + "_1.png"));
                            open.location = $scope.openUrl;
                        }
                    } else if (response.errorcode != 0) {
                        Msg.warning("查看回放失败！");
                    }
                });

            } else {
                RS.getTiket({ username: sysUserInfo.getuserinfo().user_Name, userId: sysUserInfo.getuserinfo().user_ID, orgId: sysUserInfo.getuserinfo().organization_ID }).then(function (response) {
                    if (response.errorcode == "0") {
                        var data = JSON.parse(response.data);
                        if (data.state == "101") {
                            $scope.openUrl = section.liveObj.teach_htm + "?ticket=" + data.ticket + "&uid=" + sysUserInfo.getuserinfo().user_ID + "&uname=" + encodeURI(encodeURI(sysUserInfo.getuserinfo().user_Name)) + "&img=" + encodeURI(encodeURI($rootScope.fileurl + "/resources/logo/" + sysUserInfo.getuserinfo().organization_ID + "_1.png"));
                            //                        var url = document.getElementById("courseUrl");
                            //                        url.href = $scope.openUrl;
                            //                        url.click();
                            //                        var openLink = $("#courseUrl");
                            //                        openLink.attr('href', $scope.openUrl);
                            //                        $timeout(function () { openLink[0].click(); }, 1000);
                            open.location = $scope.openUrl;
                        }
                    } else if (response.errorcode != 0) {
                        Msg.warning("进入直播失败！");
                    }
                });
            }
        }
    }

    //************************************负责人*****************************************//
    // 人员选择器
    //批量添加负责人 选择器初始化
    $scope.personDataUser = {

        ApiOpen: false,
        style: "",
        menu: [{ "id": "User"}],
        UserList: [],
        ViceuserOrgList: [],
        ViceuserRuleList: [],
        ViceuserGroupList: [],
        searchType: [],  //初始化教师查询
        //                 searchTexts: 3,  // 初始化教师查询
        DB: "0",
        DBdata: []

    }

    // 新增负责人
    $scope.showPersonSelect = function (event) {
        $scope.personDataUser.style = $scope.mousePosition(event);
        $scope.personDataUser.ApiOpen = true;
    }
    //获取负责人
    $scope.getPerson = function () {
        RS.findRelationPeople({ userId: sysUserInfo.getuserinfo().user_ID, xid: $scope.traininfo.courseId, xtype: 1 }).then(function (data) {
            if (data.errorcode == "0" && data.datas != undefined) {
                $scope.personDataUser.UserList = data.datas;
            }
        });
    }



    //配置富文本编辑器的按钮
    $scope.configCourseDetailed = ['undo', 'redo', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', '|', 'quote', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright', '|', 'img', 'insertcode'];
    //富文本编辑器配置
    $scope.showfileTxt = false;
    $scope.showFileText = function () {
        $scope.showfileTxt = !$scope.showfileTxt;
    }

    //选择问卷
    $scope.addQuestionaire = function () {
        if ($scope.knowConfig.isShow) {
            $scope.knowConfig.isShow = false;
        } else {
            $scope.knowConfig.qunaireList = [];
            $scope.knowConfig.menu = ["qunaire"];
            $scope.knowConfig.isShow = true;
        }
    }
    $scope.QuestionaireObj = {}; //当前选中的对象
    //knowConfig选择器回调
    $scope.configCallBack = function () {
        if ($scope.knowConfig.qunaireList.length > 0) {
            $scope.QuestionaireObj = $scope.knowConfig.qunaireList[0];
        }
    }

    /***********************************直播*********************************** */

    $scope.knowLiveConfig = {   // 配置知识选择器
        menu: ["live"],
        liveMore: false, //是否多选
        liveList: [],    // 选中列表               
        isShow: false  // 显示
    };
    //直播回调
    $scope.configCallBackLive=function(){
        if($scope.knowLiveConfig.liveList.length>0){
            $scope.liveSetion.liveId=$scope.knowLiveConfig.liveList[0].roomId;
            $scope.liveSetion.CSNAME=$scope.knowLiveConfig.liveList[0].liveName;
        }
    }

    $scope.liveSetion={};
    //打开直播间选择器
    $scope.openLiveSelect=function(xiaojie){
        $scope.liveSetion=xiaojie;
        $scope.knowLiveConfig.isShow=true;
    }

} ]);
